<?php namespace kisay\Service\Form\Article;

use kisay\Service\Form\Tag\TagInterface;
use Illuminate\Database\Eloquent\Model;

class ArticleEloquent implements ArticleInterface{

    public function __construct(Model $article, TagInterface $tag)
    {
        $this->article = $article;
        $this->tag = $tag;
    }

    public function byPage($page=1, $pagesize=10)
    {
        $articles = $this->article->with('tags')
                        ->where('state', 1)
                        ->orderBy('created_at', 'desc')
                        ->skip($pagesize*($page-1))
                        ->take($pagesize)
                        ->get();
        //创建一个可用于分页的返回结果
        $data = new \StdClass;
        $data->items = $articles->all();
        $data->totolItems = $articles->totalRows();

        return $data;
    }

    /*
     *返回第一条结果
     */
    public function bySlug($slug)
    {
        return $this->article->with('tags')
                    ->where('slug', $slug)
                    ->first();
    }

    /*
     *根据标签查找文章前先判断是否存在该标签
     */
    public function byTag($tag, $page=1, $rows=10)
    {
        $foundTag = $this->tag->bySlug($tag);
        $data = new \StdClass;
        if (empty($foundTag)
        {
            $data->items = array();
            $data->totalItems = 0; 
        }else {
           $articles = $this->tag->articles()
                ->where('state',0)
                ->order('article.published_at', 'desc')
                ->skip($rows*($page-1))
                ->take($rows)
                ->get();
           $data->items = $articles->all();
           $data->totalItems - $articles->totalByTag();
        }
        return $data;
    }
}
